package no.monsen.client.common;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.URI;
import java.util.List;
import java.util.Properties;

import no.monsen.client.common.logging.Logger;

import org.apache.commons.logging.Log;

/**
 * @author Marius Breivik
 */
public class MonsenConnectionConfigurer {

	@Logger
	private Log log;
	
	public void configureConnection() {
		log.debug("Configuring connection...");
		try {
			System.setProperty("java.net.useSystemProxies", "true");
			List<Proxy> proxyList = ProxySelector.getDefault().select( new URI("http://www.yahoo.com/") );

			for (Proxy proxy : proxyList) {
				log.debug("Connection type: " + proxy.type());
				InetSocketAddress addr = (InetSocketAddress) proxy.address();
				if (addr != null) {
					log.debug("Proxy settings detected: \n");
					log.debug("proxy hostname: " + addr.getHostName());
					log.debug("poxy port: " + addr.getPort());
					configureAutoDetectedProxySettings( addr );
				} else {
					log.debug("No proxy connection detected. Using default settings.");
				}
			}
		} catch (Exception e) {
			log.error( e );
		}
	}
	
	private void configureAutoDetectedProxySettings( InetSocketAddress socketAddress ){
		log.debug("Writing proxy setting..");
		Properties props = new Properties(System.getProperties());
        props.put("http.proxySet", "true");
        
        log.debug("Setting http.proxyHost to: " );
        props.put("http.proxyHost", socketAddress.getHostName());
        log.debug("Setting proxyPort to: " + socketAddress.getPort() );
        props.put("http.proxyPort", socketAddress.getPort());
        Properties newprops = new Properties(props);
        System.setProperties(newprops);
	}
}
